<script setup lang="ts">
import { ref } from 'vue';
import { type Card } from '@/types/card';
import { Check, type CheckList } from '@/types/check';
import NdButton from '@/components/modules/NdButton.vue';

// 内部状态
const visiable = ref(false);
const cardData = ref<{
    card: Card | null,
    title: string,
    content: string,
    checkLists: Array<CheckList>
}>({
    card: null,
    title: '',
    content: '',
    checkLists: []
});
// 标题编辑状态
const editingTitleType = ref(false);
const editedTitle = ref('');
// 内容编辑状态
const editingContentType = ref(false);
const editedContent = ref('');
// 新增待办事项列表
const checkListAddData = ref({
    type: false,
    checklistId: '',
    checklistTitle: ''
});
// 新增待办事项
const checkAddData = ref({
    type: false,
    checklistId: '',
    checklistTitle: ''
});
// 关闭弹窗
const onCloseModal = () => {
    visiable.value = false;
};

// 更变标题编辑状态
const onChangeEditingTitle = (type: boolean) => {
    editingTitleType.value = type;
    if(type){
        editedTitle.value = cardData.value?.title || '';
    }
};

// 保存标题
const onSaveTitle = () => {
    if (editedTitle.value.trim() && cardData.value) {
        cardData.value = {
            ...cardData.value,
            title: editedTitle.value
        };
        if(cardData.value.card){
            cardData.value.card.title = editedTitle.value;
        }
        fetch(`/api/card/${cardData.value.card?.cardId}`, {
            method: 'PUT',
            body: JSON.stringify({
                title: editedTitle.value
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }
    editingTitleType.value = false;
};

// 更变内容编辑状态
const onChangeEditingContent = (type: boolean) => {
    editingContentType.value = type;
    if(type){
        editedContent.value = cardData.value?.content || '';
    }
};

// 保存内容
const onSaveContent = () => {
    if (cardData.value) {
        cardData.value = {
            ...cardData.value,
            content: editedContent.value
        };
        fetch(`/api/card/${cardData.value.card?.cardId}`, {
            method: 'PUT',
            body: JSON.stringify({
                content: editedContent.value
            }),
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }
    editingContentType.value = false;
};

// 设置添加checklist状态
const onSetCheckListAddType = (type: boolean) => {
    checkListAddData.value.type = type;
};

// 添加新的待办事项列表
const onAddChecklist = () => {
    if (checkListAddData.value.checklistTitle.trim() && cardData.value) {
        let newList: CheckList = {
            title: checkListAddData.value.checklistTitle.trim()
        };
        fetch(`/api/card/${cardData.value.card?.cardId}/checklist`, {
            method: 'POST',
            body: JSON.stringify(newList),
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(res => res.json()).then(res => {
            const data = res['data'] as CheckList;
            newList = {
                ...newList,
                ...data
            };
            cardData.value.checkLists.unshift(newList);
        });
        checkListAddData.value.checklistTitle = '';
        checkListAddData.value.type = false;
    }
};

// 设置添加check状态
const onSetCheckAddType = (checklistId: string, type: boolean) => {
    checkAddData.value.type = type;
    checkAddData.value.checklistId = checklistId;
};

// 添加待办事项
const onAddCheck = (checklistId: string) => {
    if (checkAddData.value.checklistTitle.trim() && cardData.value) {
        const checklist = cardData.value.checkLists.find(list => list.checkListId === checklistId);
        if (checklist) {
            let newItem = {
                title: checkAddData.value.checklistTitle.trim()
            };
            fetch(`/api/checklist/${checklistId}/check`, {
                method: 'POST',
                body: JSON.stringify(newItem),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(res => res.json()).then(res => {
                const data = res['data'] as Check;
                newItem = {
                    ...newItem,
                    ...data
                };
                checklist.checks?.push(newItem);
            });
            checkAddData.value.checklistTitle = '';
            checkAddData.value.type = false;
        }
    }
};

// 更新待办事项状态
const onUpdateChecklistItem = (checklistId: string, itemId: string, data: {
    completed?: boolean,
    title?: string
}) => {
    if (cardData.value) {
        const checklist = cardData.value.checkLists.find(list => list.checkListId === checklistId);
        if (checklist) {
            fetch(`/api/check/${itemId}`, {
                method: 'PUT',
                body: JSON.stringify(data),
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        }
    }
};

// 删除待办事项
const onRemoveChecklistItem = (checklistId: string, itemId: string) => {
    if (cardData.value) {
        const checklist = cardData.value.checkLists.find(list => list.checkListId === checklistId);
        if (checklist) {
            checklist.checks = checklist.checks?.filter(item => item.checkId !== itemId) || [];
            fetch(`/api/check/${itemId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        }
    }
};

// 删除整个待办事项列表
const onRemoveChecklist = (checklistId: string) => {
    if (cardData.value) {
        cardData.value.checkLists = cardData.value.checkLists.filter(list => list.checkListId !== checklistId);
        fetch(`/api/checklist/${checklistId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json'
            }
        });
    }
};

// 计算特定列表已完成的待办事项数量
const completedCount = (checklist: CheckList) => {
    return checklist.checks?.filter(item => item.completed).length || 0;
};

// 阻止冒泡，防止点击卡片详情内部元素时关闭弹窗
const stopPropagation = (e: Event) => {
    e.stopPropagation();
};

// 设置显示/隐藏状态
const setVisible = (type: boolean) => {
    visiable.value = type;
};

// 设置卡片数据
const setCardData = (card: Card) => {
    cardData.value.card = card;
    fetch(`/api/card/${card.cardId}`).then((res) => {
        res.json().then(res => {
            const data = res['data'] as Card;
            cardData.value.title = data.title || '';
            cardData.value.content = data.content || '';
        });
    });
    fetch(`/api/card/${card.cardId}/checklist`).then((res) => {
        res.json().then(res => {
            const data = res['data'] as Array<CheckList>;
            cardData.value.checkLists = data;
        });
    });
};

// 只暴露需要的两个方法
defineExpose({
    setVisible,
    setCardData
});
</script>

<template>
	<div
		v-if="visiable"
		class="card-detail-overlay"
		@click="onCloseModal"
	>
		<div
			class="card-detail-modal"
			@click="stopPropagation"
		>
			<!-- 标题区域 -->
			<div class="card-detail-header">
				<div
					v-if="!editingTitleType"
					class="card-detail-title"
					@click="onChangeEditingTitle(true)"
				>
					{{ cardData.title }}
				</div>
				<div
					v-else
					class="card-title-edit"
				>
					<input
						v-model="editedTitle"
						type="text"
						class="title-input"
						autoFocus
						@blur="onSaveTitle"
						@keydown.enter="onSaveTitle"
					>
				</div>
				<div class="created-time">
					创建于: {{ new Date(cardData?.card?.createdAt || Date.now()).toLocaleString() }}
				</div>
				<nd-button
					type="default"
					class="close-button"
					@click="onCloseModal"
				>
					×
				</nd-button>
			</div>

			<div class="card-detail-content-container">
				<div class="left-container">
					<!-- 内容区域 -->
					<div class="card-detail-content">
						<div class="section-header">
							<h3>描述</h3>
							<nd-button
								v-if="!editingContentType"
								type="default"
								plain
								class="edit-button"
								@click="onChangeEditingContent(true)"
							>
								编辑
							</nd-button>
						</div>

						<div
							v-if="!editingContentType"
							class="content-display"
						>
							<p v-if="cardData.content">
								{{ cardData.content }}
							</p>
							<p
								v-else
								class="empty-content"
							>
								添加详细描述...
							</p>
						</div>
						<div
							v-else
							class="content-edit"
						>
							<textarea
								v-model="editedContent"
								class="content-textarea"
								placeholder="添加详细描述..."
								rows="6"
							/>
							<div class="edit-actions">
								<nd-button
									type="success"
									class="save-button"
									@click="onSaveContent"
								>
									保存
								</nd-button>
								<nd-button
									type="default"
									plain
									class="cancel-button"
									@click="onChangeEditingContent(false)"
								>
									取消
								</nd-button>
							</div>
						</div>
					</div>

					<!-- 待办事项列表部分 -->
					<div class="card-detail-checklists">
						<div class="section-header">
							<h3>待办事项清单</h3>
						</div>

						<!-- 新增待办事项列表表单 -->
						<div
							v-if="checkListAddData.type"
							class="add-checklist-form"
						>
							<input
								v-model="checkListAddData.checklistTitle"
								type="text"
								placeholder="输入清单名称..."
								@keydown.enter="onAddChecklist"
							>
							<div class="edit-actions">
								<nd-button
									type="success"
									class="save-button"
									@click="onAddChecklist"
								>
									添加
								</nd-button>
								<nd-button
									type="default"
									plain
									class="cancel-button"
									@click="onSetCheckListAddType(false)"
								>
									取消
								</nd-button>
							</div>
						</div>

						<!-- 待办事项列表 -->
						<div 
							v-for="checklist in cardData.checkLists" 
							:key="checklist.checkListId" 
							class="checklist-container"
						>
							<div class="checklist-header">
								<h4>{{ checklist.title }}</h4>
								<div class="progress-indicator">
									{{ completedCount(checklist) }} / {{ checklist.checks?.length || 0 }}
									<nd-button
										type="error"
										plain
										class="delete-button"
										@click="onRemoveChecklist(checklist?.checkListId || '')"
									>
										删除
									</nd-button>
								</div>
							</div>

							<div class="progress-bar">
								<div
									class="progress"
									:style="{ width: checklist.checks?.length ? `${(completedCount(checklist) / checklist.checks.length) * 100}%` : '0%' }"
								/>
							</div>

							<ul class="checklist-items">
								<li
									v-for="item in checklist.checks"
									:key="item.checkId"
									class="checklist-item"
								>
									<label class="checkbox-container">
										<input
											v-model="item.completed"
											type="checkbox"
											@change="onUpdateChecklistItem(checklist?.checkListId || '', item?.checkId || '', {completed: item.completed})"
										>
										<span class="checkmark" />
									</label>
									<span
										class="title"
										:class="{ 'completed': item.completed }"
									>{{ item.title }}</span>
									<div
										class="delete-btn-icon"
										@click="onRemoveChecklistItem(checklist?.checkListId || '', item.checkId || '')"
									>
										×
									</div>
								</li>
							</ul>
							<div
								v-if="checkAddData.type && checkAddData.checklistId === checklist?.checkListId"
								class="add-checklist-item"
							>
								<input
									v-model="checkAddData.checklistTitle"
									type="text"
									placeholder="添加新的待办事项..."
									@keydown.enter="onAddCheck(checklist?.checkListId || '')"
								>
								<div class="btns">
									<nd-button
										type="success"
										@click="onAddCheck(checklist?.checkListId || '')"
									>
										添加
									</nd-button>
									<nd-button
										type="default"
										plain
										@click="onSetCheckAddType(checklist?.checkListId || '', false)"
									>
										取消
									</nd-button>
								</div>
							</div>
							<nd-button
								v-else
								type="default"
								plain
								class="add-check-btn"
								@click="onSetCheckAddType(checklist?.checkListId || '', true)"
							>
								+ 清单项
							</nd-button>
						</div>
					</div>
				</div>
				<div class="right-container">
					<nd-button
						class="btn"
						type="success"
						@click="onSetCheckListAddType(true)"
					>
						+ 清单
					</nd-button>
				</div>
			</div>
		</div>
	</div>
</template>
<style lang="scss" scoped>
@import '@/assets/scss/components/card-detail.scss';
</style>